<template>
  <div class="app-container">
    <el-card class="contentBox">
      <h1 class="title">{{ title }}</h1>
      <p class="subTitle">{{ subTitle }}</p>
      <div class="kill-margin">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12">
            <el-card>
              <template #header>
                <div class="card-header">
                  <span>视频生成设置</span>
                </div>
              </template>
              <el-form
                ref="form"
                :model="form"
                :rules="rules"
                label-position="top"
              >
                <el-form-item
                  label="上传图片"
                  prop="picUrl"
                  v-if="taskType === 2"
                >
                  <el-alert
                    title="暂不支持上传人像图片"
                    type="error"
                    show-icon
                    :closable="false"
                  >
                    <template #icon>
                      <InfoFilled></InfoFilled>
                    </template>
                    当前暂不支持包含真人的人像图片，请上传风景、物品、动物等内容。
                  </el-alert>
                  <image-upload
                    v-model="form.picUrl"
                    :limit="1"
                    :file-size="20"
                  ></image-upload>
                </el-form-item>
                <el-form-item label="视频时长" prop="seconds" size="large">
                  <el-radio-group
                    v-model="form.seconds"
                    class="full-radio-group"
                  >
                    <el-radio-button label="10s" :value="10" />
                    <el-radio-button label="15s" :value="15" />
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="画面模式" prop="videoType">
                  <el-radio-group
                    v-model="form.videoType"
                    size="large"
                    class="full-radio-group"
                  >
                    <el-radio-button label="9:16竖屏" :value="2" />
                    <el-radio-button label="16:9横屏" :value="1" />
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="视频描述" prop="des">
                  <el-input
                    :rows="6"
                    v-model="form.des"
                    type="textarea"
                    placeholder="请输入内容"
                    show-word-limit
                    maxlength="5000"
                  />
                </el-form-item>
                <div class="polish-wrap" v-if="gptConfigs?.length">
                  <div class="polish-content" v-if="polish.isPolished">
                    <div class="polish-tips">
                      以下为 AI 润色的内容，您可以应用此内容或对其再次编辑
                    </div>
                    <div class="polish-input">
                      <el-input
                        :rows="6"
                        v-model="polish.content"
                        type="textarea"
                        placeholder="请输入内容"
                        show-word-limit
                        maxlength="5000"
                      />
                    </div>
                  </div>
                  <div class="polish-buttons">
                    <div class="polish-select">
                      <el-select
                        v-model="gptId"
                        :options="gptConfigs"
                        placeholder="选择润色模板"
                      ></el-select>
                    </div>
                    <template v-if="!polish.isPolished">
                      <el-button
                        @click="polishDesc"
                        :loading="polish.loading"
                        type="primary"
                        plain
                        icon="MagicStick"
                        :disabled="!gptId"
                      >
                        <template v-if="polish.loading">润色中...</template>
                        <template v-else>AI 润色</template>
                      </el-button>
                    </template>
                    <template v-else>
                      <el-button
                        :loading="polish.loading"
                        @click="polishDesc"
                        type="primary"
                        plain
                        icon="MagicStick"
                      >
                        <template v-if="polish.loading">润色中...</template>
                        <template v-else>重新润色</template>
                      </el-button>
                      <el-button
                        type="primary"
                        @click="polishApply"
                        icon="Select"
                        >应用此内容</el-button
                      >
                    </template>
                  </div>
                </div>
                <el-form-item label="批量生成" prop="count">
                  <el-radio-group
                    v-model="form.count"
                    size="large"
                    class="full-radio-group"
                  >
                    <el-radio-button label="1条" :value="1" />
                    <el-radio-button label="3条" :value="3" />
                    <el-radio-button label="5条" :value="5" />
                    <el-radio-button label="10条" :value="10" />
                  </el-radio-group>
                </el-form-item>
              </el-form>
              <el-button
                @click="submitForm"
                type="primary"
                size="large"
                icon="VideoCamera"
                style="width: 100%"
                :loading="loading"
                >生成视频</el-button
              >
              <el-divider></el-divider>
              <TipsPic v-if="taskType === 2"></TipsPic>
              <TipsText v-else></TipsText>
            </el-card>
          </el-col>
          <el-col :xs="24" :sm="12">
            <el-card>
              <template #header>
                <div class="card-header">
                  <span>生成任务</span>
                </div>
              </template>
              <TaskLog :task-id="currentTask?.id"></TaskLog>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </el-card>
  </div>
</template>
<script>
import { addTask, promptPolish, queryGptConfig } from '../../api/task';
import TaskLog from './task-log.vue';
import TipsPic from './tipsPic.vue';
import TipsText from './tipsText.vue';
import { InfoFilled } from '@element-plus/icons-vue';

export default {
  name: 'UserTask',
  components: { TaskLog, TipsPic, TipsText, InfoFilled },
  props: {
    taskType: {
      type: Number,
      default: 2,
    },
  },
  data() {
    return {
      loading: false,
      // 表单参数
      form: {
        seconds: 15,
        videoType: 2,
        count: 1,
      },
      // 表单校验
      rules: {
        picUrl: [{ required: true, message: '请选择图片！', trigger: 'blur' }],
        seconds: [
          { required: true, message: '视频时长不能为空', trigger: 'blur' },
        ],
        videoType: [
          { required: true, message: '画面模式不能为空', trigger: 'change' },
        ],
        des: [{ required: true, message: '视频描述不能为空', trigger: 'blur' }],
      },
      currentTask: null,
      polish: {
        isPolished: false,
        content: '',
        loading: false,
      },
      gptConfigs: [],
      gptId: null,
    };
  },
  computed: {
    title() {
      return this.$props.taskType === 1 ? '文案生成视频' : '图片生成视频';
    },
    subTitle() {
      return this.$props.taskType === 1
        ? '输入文本描述，AI将为您生成精彩的视频内容'
        : '上传图片并添加文字描述，AI将为您生成动态视频内容';
    },
  },
  mounted() {
    this.queryGptConfig();
    const reEditData = this.$router.options.history.state;
    if (reEditData) {
      this.form.des = reEditData.des || '';
      this.form.count = reEditData.count || 1;
      this.form.seconds = reEditData.seconds || 15;
      this.form.videoType = reEditData.videoType || 2;
      if (this.$props.taskType === 2) {
        this.form.picUrl = reEditData.picUrl || '';
      }
    }
  },
  methods: {
    /** 提交按钮 */
    async submitForm() {
      await this.$refs.form.validate();
      try {
        this.loading = true;
        const { count, des, picUrl, ...rest } = this.form;
        rest.simpleTaskList = new Array(count).fill(null).map((_, i) => {
          const prefix = count === 1 ? '' : `${i + 1}. `;
          return {
            des: `${prefix}${des}`,
            picUrl: picUrl,
          };
        });
        const res = await addTask({
          ...rest,
          taskType: this.$props.taskType,
        });
        this.currentTask = res.data;
        this.$message.success('任务提交成功！');
        this.$refs.form.resetFields();
      } catch (error) {
        // this.$message.error(error.message || '任务提交失败！');
      } finally {
        this.loading = false;
      }
    },
    async queryGptConfig() {
      const res = await queryGptConfig();
      this.gptConfigs = (res.data || []).map((item) => {
        return { value: item.id, label: item.name || '未命名模板' };
      });
    },
    async polishDesc() {
      this.polish.loading = true;
      // 调用提示词润色接口
      const res = await promptPolish({
        gptId: this.gptId,
        des: this.form.des,
        picUrl: this.form.picUrl,
      }).finally(() => {
        this.polish.loading = false;
      });
      try {
        const data = JSON.parse(res.data);
        const args = JSON.parse(
          data.choices[0].message.tool_calls[0].function.arguments,
        );
        this.polish.content = `# 标题：${args.title}
# 关键字：${args.keywords?.join('、')}

        ${args.content}`;
        this.polish.isPolished = true;
      } catch (error) {
        this.$message.error('内容解析错误！');
      }
    },
    polishApply() {
      this.form.des = this.polish.content;
      this.polish.isPolished = false;
      this.polish.loading = false;
    },
  },
};
</script>
<style scoped lang="scss">
.subTitle {
  color: #8c8c8c;
  font-size: 16px;
}
.polish {
  &-content {
    background: var(--el-color-primary);
    border-radius: 4px;
    :deep(.el-textarea__inner) {
      box-shadow: none;
      background: var(--el-color-primary-light-9);
      padding: 18px;
    }
  }
  &-tips {
    padding: 12px;
    font-size: 14px;
    color: #fff;
  }
  &-buttons {
    display: flex;
    justify-content: flex-end;
    margin-top: 12px;
  }
  &-select {
    margin-right: 12px;
    width: 200px;
  }
}
</style>
